package org.cbyyx.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cbyyx.tc.common.LoginLocal;
import org.cbyyx.tc.enums.ErrorCode;
import org.cbyyx.tc.exception.ThrowUtils;
import org.cbyyx.tc.mapper.AddressMapper;
import org.cbyyx.tc.model.dto.addressRequest.AddressAddRequest;
import org.cbyyx.tc.model.dto.addressRequest.AddressQueryRequest;
import org.cbyyx.tc.model.dto.addressRequest.AddressUpdateRequest;
import org.cbyyx.tc.model.entity.Address;
import org.cbyyx.tc.model.vo.addressResponse.AddressVO;
import org.cbyyx.tc.model.vo.userResponse.UserVO;
import org.cbyyx.tc.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cbyyx
 * @description 针对表【address】的数据库操作Service实现
 * @createDate 2025-04-21 15:40:03
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    public boolean addAddress(AddressAddRequest request) {
        Address address = new Address();
        BeanUtils.copyProperties(request, address);
        return this.save(address);
    }

    @Override
    public boolean updateAddress(AddressUpdateRequest request) {
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);

        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getId, request.getId());
        wrapper.eq(Address::getUserId, loginUser.getId());
        wrapper.set(request.getIsDefault() != null, Address::getIsDefault, request.getIsDefault());
        wrapper.set(request.getReceiverName() != null, Address::getRecipientName, request.getReceiverName());
        wrapper.set(request.getPhone() != null, Address::getPhone, request.getPhone());
        wrapper.set(request.getProvince() != null, Address::getProvince, request.getProvince());
        wrapper.set(request.getCity() != null, Address::getCity, request.getCity());
        wrapper.set(request.getDistrict() != null, Address::getDistrict, request.getDistrict());
        wrapper.set(request.getAddress() != null, Address::getAddress, request.getAddress());
        if (!this.update(wrapper)) {
            Address address = this.getById(request.getId());
            ThrowUtils.throwIf(address == null, ErrorCode.PARAMS_ERROR, "地址不存在");
            ThrowUtils.throwIf(address.getUserId().longValue() != loginUser.getId().longValue(), ErrorCode.PARAMS_ERROR, "不属于当前用户");
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteAddress(Long id) {
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        Address address = this.getById(id);
        ThrowUtils.throwIf(address == null, ErrorCode.PARAMS_ERROR, "地址不存在");
        ThrowUtils.throwIf(address.getUserId().longValue() != loginUser.getId().longValue(), ErrorCode.PARAMS_ERROR, "不属于当前用户");
        ThrowUtils.throwIf(address.getIsDefault() == 1, ErrorCode.PARAMS_ERROR, "默认地址不能删除");
        return this.removeById(id);
    }

    @Override
    public AddressVO getAddress(Long id) {
        Address address = this.getById(id);
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(address == null, ErrorCode.PARAMS_ERROR, "地址不存在");
        ThrowUtils.throwIf(address.getUserId().longValue() != loginUser.getId().longValue(), ErrorCode.PARAMS_ERROR, "不属于当前用户");
        AddressVO vo = new AddressVO();
        BeanUtils.copyProperties(address, vo);
        return vo;
    }

    @Override
    public AddressVO getDefaultAddress() {
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("isDefault", 1);
        wrapper.eq("userId", loginUser.getId());
        Address address = this.getOne(wrapper);
        if (address == null) {
            return null;
        }
        AddressVO vo = new AddressVO();
        BeanUtils.copyProperties(address, vo);
        return vo;
    }

    @Override
    public List<AddressVO> listAddresses(AddressQueryRequest request) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        wrapper.eq("userId", loginUser.getId());
        List<Address> addresses = this.list(wrapper);
        return addresses.stream().map(address -> {
            AddressVO vo = new AddressVO();
            BeanUtils.copyProperties(address, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean setDefaultAddress(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR, "地址ID无效");
        // 1. 先将所有地址设为非默认
        UserVO loginUser = LoginLocal.getLoginUser();
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        this.update(new UpdateWrapper<Address>()
                .eq("userId", loginUser.getId())
                .set("isDefault", 0));

        // 2. 将指定ID的地址设为默认
        return this.update(new UpdateWrapper<Address>()
                .eq("id", id)
                .eq("userId", loginUser.getId())
                .set("isDefault", 1));
    }
}




